<!--
文件名: src/views/order/history/index.vue
功能: 历史订单 (使用记录) 管理列表页
描述: 包含筛选、分页、编辑、删除和导出功能。 (已根据嵌套数据结构修正)
-->
<template>
  <div class="app-container">
    <!-- 1. 筛选与操作区 -->
    <el-card shadow="never">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="query-form">
        <el-form-item label="使用人" prop="actual_user_name">
          <el-input v-model="queryParams.actual_user_name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="联系电话" prop="actual_user_phone">
          <el-input v-model="queryParams.actual_user_phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="课题组" prop="actual_user_group">
          <el-input v-model="queryParams.actual_user_group" placeholder="请输入课题组" clearable />
        </el-form-item>

        <el-form-item label="使用设备" prop="device_id">
          <el-select v-model="queryParams.device_id" placeholder="请选择设备" clearable>
            <el-option
              v-for="device in deviceOptions"
              :key="device.id"
              :label="device.name"
              :value="device.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="使用日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 2. 数据表格区 -->
    <el-card shadow="never" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>历史订单</span>
          <el-button type="success" :icon="Download" @click="handleExport" :loading="exportLoading"
            >导出 Excel</el-button
          >
        </div>
      </template>

      <el-table v-loading="loading" :data="usageRecordList">
        <el-table-column label="ID" prop="id" width="180" align="center" />
        <el-table-column
          label="使用设备"
          prop="reservation.device.name"
          width="220"
          align="center"
        />
        <el-table-column label="使用人" prop="actual_user_name" width="100" align="center" />
        <el-table-column label="联系电话" prop="actual_user_phone" width="140" align="center" />
        <el-table-column label="课题组" prop="actual_user_group" width="200" align="center" />
        <el-table-column label="开始时间" prop="actual_start_time" width="180" align="center" />
        <el-table-column label="结束时间" prop="actual_end_time" width="180" align="center" />
        <el-table-column label="时长(min)" prop="total_minutes_used" width="110" align="center" />
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="scope">
            <el-button type="info" link :icon="View" @click="handleViewRemarks(scope.row)"
              >备注</el-button
            >
            <el-button type="primary" link :icon="Edit" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="total > 0"
        v-model:current-page="queryParams.page"
        :page-size="queryParams.size"
        :total="total"
        layout="total, prev, pager, next, jumper"
        @current-change="getList"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>

    <!-- 3. 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogCancel"
    >
      <el-form :model="editForm" ref="editFormRef" label-width="100px">
        <el-form-item label="使用人" prop="actual_user_name">
          <el-input v-model="editForm.actual_user_name" placeholder="请输入使用人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="actual_user_phone">
          <el-input v-model="editForm.actual_user_phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="课题组" prop="actual_user_group">
          <el-input v-model="editForm.actual_user_group" placeholder="请输入课题组" />
        </el-form-item>
        <el-form-item label="实际开始时间" prop="actual_start_time">
          <el-date-picker
            v-model="editForm.actual_start_time"
            type="datetime"
            placeholder="选择实际开始时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="实际结束时间" prop="actual_end_time">
          <el-date-picker
            v-model="editForm.actual_end_time"
            type="datetime"
            placeholder="选择实际结束时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="editForm.remarks" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogCancel">取 消</el-button>
        <el-button type="primary" @click="handleDialogSubmit">确 定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="remarksDialogVisible" title="查看备注" width="500px">
      <div class="remarks-content">
        {{ currentRemarks }}
      </div>
      <template #footer>
        <el-button type="primary" @click="remarksDialogVisible = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import {
  getUsageRecordListApi,
  deleteUsageRecordApi,
  updateUsageRecordApi,
  getAllDevicesApi,
  exportUsageRecordsApi,
} from '@/api'
import type {
  UsageRecordListParams,
  UsageRecordDetail,
  UsageRecordManualUpdate,
} from '@/api/types/usageRecord'
import type { Device } from '@/api/types/device'
import { Search, Refresh, Download, Edit, Delete, View } from '@element-plus/icons-vue'

const loading = ref(true)
const exportLoading = ref(false)
const total = ref(0)
const queryFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()

const usageRecordList = ref<UsageRecordDetail[]>([])
const deviceOptions = ref<Device[]>([])
const dateRange = ref<[string, string] | null>(null)

// --- 对话框相关状态 ---
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentRecordId = ref<number | null>(null)
// 使用 UsageRecordManualUpdate 作为表单类型
const editForm = reactive<UsageRecordManualUpdate>({
  actual_user_name: '',
  actual_user_phone: '',
  actual_user_group: '',
  actual_start_time: '',
  actual_end_time: '',
  remarks: '',
})
const remarksDialogVisible = ref(false)
const currentRemarks = ref('')
const queryParams = reactive<UsageRecordListParams>({
  page: 1,
  size: 10,
  actual_user_name: undefined,
  actual_user_phone: undefined,
  actual_user_group: undefined,
  device_id: undefined,
  start_date: undefined,
  end_date: undefined,
})

const getList = async () => {
  loading.value = true
  try {
    queryParams.start_date = dateRange.value?.[0]
    queryParams.end_date = dateRange.value?.[1]
    const response = await getUsageRecordListApi(queryParams)
    usageRecordList.value = response.items
    total.value = response.total
  } catch (error) {
    console.error('获取使用记录列表失败:', error)
  } finally {
    loading.value = false
  }
}

const getDevices = async () => {
  try {
    deviceOptions.value = await getAllDevicesApi()
  } catch (error) {
    console.error('获取设备选项失败:', error)
    deviceOptions.value = []
  }
}

const handleQuery = () => {
  queryParams.page = 1
  getList()
}

/** 重置按钮操作 */
const handleReset = () => {
  queryFormRef.value?.resetFields()
  dateRange.value = null
  handleQuery()
}
/** 查看备注按钮操作 */
const handleViewRemarks = (row: UsageRecordDetail) => {
  currentRemarks.value = row.remarks || '暂无备注'
  remarksDialogVisible.value = true
}
/** 编辑按钮操作 */
const handleEdit = (row: UsageRecordDetail) => {
  currentRecordId.value = row.id
  // 填充表单
  editForm.actual_user_name = row.actual_user_name || ''
  editForm.actual_user_phone = row.actual_user_phone || ''
  editForm.actual_user_group = row.actual_user_group || ''
  editForm.actual_start_time = row.actual_start_time || ''
  editForm.actual_end_time = row.actual_end_time || ''
  editForm.remarks = row.remarks || ''
  // 显示对话框
  dialogTitle.value = `编辑记录 (ID: ${row.id})`
  dialogVisible.value = true
}

/** 删除按钮操作 */
const handleDelete = async (row: UsageRecordDetail) => {
  try {
    await ElMessageBox.confirm(
      `确认要删除用户 [${row.actual_user_name}] 的这条使用记录吗？此操作不可恢复。`,
      '警告',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
    await deleteUsageRecordApi(row.id)
    ElMessage.success('删除成功')
    getList() // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

/** 对话框提交 */
const handleDialogSubmit = async () => {
  if (!currentRecordId.value) return
  await editFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        await updateUsageRecordApi(currentRecordId.value!, editForm)
        ElMessage.success('更新成功')
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('更新失败:', error)
      }
    }
  })
}

/** 对话框取消 */
const handleDialogCancel = () => {
  dialogVisible.value = false
  currentRecordId.value = null
  editFormRef.value?.resetFields()
}

const handleExport = async () => {
  exportLoading.value = true
  try {
    const blob = await exportUsageRecordsApi(queryParams)
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = '历史订单报表.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  } finally {
    exportLoading.value = false
  }
}

onMounted(() => {
  getList()
  getDevices()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.query-form .el-select {
  min-width: 180px;
}
/* 备注内容的样式 */
.remarks-content {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #e9ecef;
  min-height: 100px;
  white-space: pre-wrap; /* 保持文本换行 */
  word-break: break-all;
}
</style>
